package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class CalculateActivity extends AppCompatActivity {
    private TextView currencyTitle;
    private EditText rmbInput;
    private TextView resultText;
    private double exchangeRate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculate);

        // 初始化视图
        currencyTitle = findViewById(R.id.tv_currency);
        rmbInput = findViewById(R.id.et_rmb_input);
        resultText = findViewById(R.id.tv_result);

        // 获取传递参数
        Intent intent = getIntent();
        String currencyName = intent.getStringExtra("CURRENCY_NAME");
        exchangeRate = intent.getDoubleExtra("EXCHANGE_RATE", 1.0);

        // 设置货币标题
        currencyTitle.setText(currencyName);

        // 设置输入监听
        rmbInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                calculateExchange(s.toString());
            }
        });
    }

    private void calculateExchange(String input) {
        if (!input.isEmpty()) {
            try {
                double rmb = Double.parseDouble(input);
                double result = rmb * exchangeRate;
                resultText.setText(String.format("%.2f", result));
            } catch (NumberFormatException e) {
                resultText.setText("输入格式错误");
            }
        } else {
            resultText.setText("0.00");
        }
    }
}